package com.aftersale.platform.controller;

import com.aftersale.platform.dto.ApiResponse;
import com.aftersale.platform.dto.UpdatePasswordRequest;
import com.aftersale.platform.entity.User;
import com.aftersale.platform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{username}")
    public ResponseEntity<ApiResponse<User>> getUserByUsername(@PathVariable String username) {
        User user = userService.findByUsername(username);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        // 不要返回密码
        user.setPassword(null);
        return ResponseEntity.ok(ApiResponse.success(user, "获取用户信息成功"));
    }

    @PutMapping("/{username}/password")
    public ResponseEntity<ApiResponse<Void>> updatePassword(@PathVariable String username,
                                                            @RequestBody UpdatePasswordRequest request) {
        User user = userService.findByUsername(username);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }

        if (request.getNewPassword() == null || request.getNewPassword().trim().isEmpty()) {
            return ResponseEntity.badRequest().body(ApiResponse.error("新密码不能为空！"));
        }

        // 验证旧密码
        // if (!user.getPassword().equals(request.getOldPassword())) {
        //     return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.error("旧密码不正确！"));
        // }

        // TODO: 密码加密存储
        user.setPassword(request.getNewPassword());
        userService.update(user);
        return ResponseEntity.ok(ApiResponse.success(null, "密码更新成功！"));
    }

    // TODO: 其他用户管理操作
}